package com.javasm.boot.oauth2.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.javasm.boot.oauth2.entity.Response;
import com.javasm.boot.oauth2.exception.MyException;
import io.jsonwebtoken.lang.Assert;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

@Component
public class WebUtils {
    /**
     * 将字符串渲染到客户端
     *
     * @param resp     待渲染的对象
     * @return null
     */
    public void renderString(Response resp) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            Assert.notNull(attributes,"ServletRequestAttributes is not null");
            HttpServletResponse response = attributes.getResponse();
            Assert.notNull(response,"HttpServletResponse is not null");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] bytes = objectMapper.writeValueAsBytes(resp);
            response.getWriter().write(new String(bytes));
            response.setStatus(resp.getCode());
        } catch (Exception e) {
            throw new MyException(e);
        }
    }


    /**
     * 将字符串渲染到客户端
     *
     * @param resp     待渲染的对象
     * @return null
     */
    public void renderString(Response resp,HttpServletResponse response) {
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] bytes = objectMapper.writeValueAsBytes(resp);
            response.getWriter().write(new String(bytes));
            response.setStatus(resp.getCode());
        } catch (Exception e) {
            throw new MyException(e);
        }
    }
}
